package com.example.demo.interseptor

import com.example.demo.utils.JwtUtil
import com.example.demo.utils.MResult
import com.google.gson.Gson
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import org.springframework.web.servlet.HandlerInterceptor
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

@Component
class AuthInterceptor : HandlerInterceptor {
    private val logger = LoggerFactory.getLogger(this.javaClass)
    private val options = "OPTIONS"
    override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
        if (request.method == options) return true
        val authorization = request.getHeader("Authorization")
        if (authorization != null) {
            val token = authorization.substring(7)
            if (JwtUtil.verifyToken(token)) {
                logger.info("Auth Success Token Effective...")
                return true
            }
        }
        logger.info("Auth Fail Token Invalid...")
        response.writer.write(Gson().toJson(buildUnauthorizedResultEntity()))
        return false
    }

    fun buildUnauthorizedResultEntity(): MResult<Nothing> {

        return MResult<Nothing>().error(403, "Auth Fail")

//        return buildResultEntity {
//            code = 403
//            message = "Auth Fail"
//        }


    }
}